package com.lms.netty.tcp.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-16 10:16
 * @Description: 数据处理类
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务器接受的数据:");
        System.out.println("长度："+len);
        System.out.println("内容："+new String(content,CharsetUtil.UTF_8));
        System.out.println("服务端收到的数据包个数："+(++count));
        System.out.println();

        //回复消息
        String responseContext = UUID.randomUUID().toString();
        MessageProtocol message = new MessageProtocol();
        message.setLen(responseContext.getBytes(StandardCharsets.UTF_8).length);
        message.setContent(responseContext.getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(message);


    }
}
